import { isNumber } from "../../utils/check";

const defalutData = {
  name: "",
  prize: "",
  amount: "",
  condition: "",
};

Component({
  properties: {
    editable: { type: Boolean, value: false },
    arrayData: { type: Array, value: [] }, // 标鱼数据列表
  },

  data: {
    popupVisible: false, // 编辑/新增弹框是否可见
    editingIndex: -1, // 当前编辑的索引, -1表示新增
    formData: {
      ...defalutData,
    },
    tableHeaders: [
      { label: "标名", key: "name" },
      { label: "奖品", key: "prize" },
      { label: "数量", key: "amount" },
      { label: "触发条件", key: "condition" },
    ],
  },

  methods: {
    // 显示新增弹框
    onAdd() {
      this.setData({
        popupVisible: true,
        editingIndex: -1,
        formData: {
          ...defalutData,
        },
      });
    },

    // 处理输入变化
    onInputChange(e) {
      const { feild } = e.currentTarget.dataset;
      console.log("---feild---xxxx---", feild, e.detail.value);

      this.setData({
        [feild]: e.detail.value,
      });
    },

    // 显示编辑弹框
    onRowTap(e) {
      if (!this.properties.editable) {
        return;
      }
      const index = e.detail.index;
      this.setData({
        editingIndex: index,
        popupVisible: true,
        formData: { ...this.data.arrayData[index] },
      });
    },

    // 请求删除
    onDelete(e) {
      const index = e.detail.index;
      wx.showModal({
        title: "确认删除",
        content: "您确定要删除这标鱼信息吗？",
        success: (res) => {
          if (res.confirm) {
            this.triggerEvent("delete", { index });
          }
        },
      });
    },

    // 保存
    onSubmit() {
      const data = this.validateForm();

      if (!data) {
        return;
      }
      this.triggerEvent("save", {
        index: this.data.editingIndex,
        data,
      });
      this.onCancel(); // 关闭弹框
    },

    // 取消
    onCancel() {
      this.setData({ popupVisible: false });
    },

    validateForm() {
      const { formData } = this.data;
      const array = [
        { key: "name", title: "请输入标名" },
        { key: "prize", title: "请输入奖品" },
        { key: "amount", title: "请输入数量" },
        // { key: "condition", title: "请输入触发条件" },
      ];
      const data = {};
      for (let index = 0; index < array.length; index++) {
        const item = array[index];
        const { key, title } = item;
        if (!formData[key] || formData[key].trim() === "") {
          wx.showToast({
            title,
            icon: "none",
          });
          return false;
        }
        data[key] = formData[key].trim();
      }
      if (!isNumber(formData.amount)) {
        wx.showToast({
          title: "数量, 请输入0-99间的整数",
          icon: "none",
        });
        return false;
      }
      data.amount = Number(data.amount);
      return data;
    },
  },
});
